package 多线程;

import java.util.concurrent.atomic.AtomicBoolean;

public class FooBar {

    private int n;
    private AtomicBoolean atomicBoolean = new AtomicBoolean(true);

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            while (!atomicBoolean.get()) {

            }
            printFoo.run();
            atomicBoolean.compareAndSet(true, false);
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            while (atomicBoolean.get()) {

            }
            printBar.run();
            atomicBoolean.compareAndSet(false, true);
        }
    }

    public static void main(String[] args) {
        FooBar fooBar = new FooBar(10);
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                try {
                    fooBar.foo(new Runnable() {
                        @Override
                        public void run() {
                            System.out.print("foo");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable runnable2 =new Runnable() {
            @Override
            public void run() {
                try {
                    fooBar.bar(new Runnable() {
                        @Override
                        public void run() {
                            System.out.print("bar");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread1 = new Thread(runnable1);
        thread1.start();
        Thread thread2 = new Thread(runnable2);
        thread2.start();

    }
}
